<template>
<div class="TVChartContainer" id="trade-view" style="height:464px;"/>
</template>

<script>
import {  widget as TvWidget  } from '../../static/charting_library/charting_library.min.js';
import datafeeds from '../components/datafeeds/datafees.js';
import event from "../assets/js/event";
// import wsmsg from "../../static/messages";

export default {
  name: 'TVChartContainer',
  props:['newbar','theme','initinterval','currentPair'],
  
  watch:{
    newbar: {
  　　　　handler(newValue, oldValue) {
              this.r(newValue);
              //this.subs[1].listener(newValue);
  　　　　}
    },
    theme:{
      handler(newValue, oldValue) {
        console.log(11, newValue, oldValue);
            if(newValue){
              this.widget.applyOverrides(this.overrides);
              this.widget.addCustomCSSFile("/static/chart.css");
            }else{
              this.widget.addCustomCSSFile("/static/chart2.css");
              this.widget.applyOverrides({
                'paneProperties.background': '#fff',
                'paneProperties.horzGridProperties.color':'#f7f8fc',
                'paneProperties.vertGridProperties.color': '#f7f8fc',
              });
            }
  　　}
    },
    initinterval:{
      handler(newValue, oldValue) {
          this.interval = newValue
  　　},
    }
  },  
  data(){
    return {
      s:function(){},
      r:function(){},
      subs : [],
      resolutions_map : new Map([ ['1', 'MN1'], ['5', 'MN5'], ['15', 'MN15'],['30', 'MN30'],  ['60', 'H1'], ['120', 'H2'], ['240', 'H4'],  ['1D', 'D1']]),
      overrides:{},
      getBarTimer: null,
      chartType:1,
      buttons:[
              {title:'Time',resolution:'1',chartType:3},
              {title:'1min',resolution:'1',chartType:1},
              {title:'5min',resolution:'5',chartType:1},
              {title:'15min',resolution:'15',chartType:1},
              {title:'30min',resolution:'30',chartType:1},
              {title:'1hour',resolution:'60',chartType:1},
              {title:'1day',resolution:'1D',chartType:1},
              {title:'1week',resolution:'1W',chartType:1},
              {title:'1month',resolution:'1M',chartType:1},
      ],
      datafeeds: new datafeeds(this),
    }
  },
  created(){
    this.overrides = {
            'paneProperties.background': '#162431', // 蜡烛样式
            'mainSeriesProperties.candleStyle.upColor': '#0DA88B',
            'mainSeriesProperties.candleStyle.downColor': '#EF5756',
            // 烛心
            'mainSeriesProperties.candleStyle.drawWick': true,
            // 烛心颜色
            'mainSeriesProperties.candleStyle.wickUpColor': '#0DA88B',
            'mainSeriesProperties.candleStyle.wickDownColor': '#EF5756',
            // 边框
            'mainSeriesProperties.candleStyle.drawBorder': true,
            'mainSeriesProperties.candleStyle.borderUpColor': '#0DA88B',
            'mainSeriesProperties.candleStyle.borderDownColor': '#EF5756',
            // 网格
            'paneProperties.vertGridProperties.style': 0,
            'paneProperties.horzGridProperties.color':'#222636',
            'paneProperties.vertGridProperties.color': '#222636',
            // 坐标轴和刻度标签颜色
            'scalesProperties.lineColor': '#252525',
            'scalesProperties.textColor': '#8a8a8a',
            'paneProperties.legendProperties.showLegend': true,
            'paneProperties.topMargin': 20,
            'paneProperties.background': '#171b2b',
          }
  },
  methods: {
    init(symbol = 'BTCUSDT', interval = 5) {
      let that = this;
      if (!this.widget) {
        this.widget = new TvWidget({
          symbol: symbol,
          width:"100%",
          height:"100%",
          theme: "Dark",
          interval: interval,
          // fullscreen: true,
          container_id: 'trade-view',
          datafeed: this.datafeeds,
          library_path: '/static/charting_library/',
          disabled_features: ['header_symbol_search','source_selection_markers','adaptive_logo','header_screenshot','volume_force_overlay','timeframes_toolbar'],
          enabled_features: [],
          timezone: 'Asia/Shanghai',
          locale: this.$i18n.locale=='zh_CN'?'zh':'en',
          debug: false,
          toolbar_bg:'transparent', // 工具栏背景颜色
          loading_screen: that.theme?{ backgroundColor: '#171b2b',foregroundColor:'#171b2b' }:{ backgroundColor: '#fff',foregroundColor:'#fff' },//加载背景色
          //overrides:this.overrides,
          // custom_css_url:'/static/chart.css',
          chartType:1
        })
        this.symbol = symbol
        this.interval = interval

        this.widget.onChartReady(function(){
            if(that.$route.fullPath=="/future" || that.$route.fullPath=="/trade"){
              that.widget.applyOverrides(that.overrides);
              that.widget.addCustomCSSFile("/static/chart.css");
            }
        });
        
      }
    },
    onRealtimeCallback(e){
      this.r = e
    },
    unSubscribe(interval) {
      
    },
    subscribe() {
      let that = this;
        that.win$.wsmsg.sendWsMsg({bar : wsmsg.BarRequest.create(that.win$.wsmsg.addRequestId({
											symbol: that.symbol,
											type  : that.resolutions_map.get(that.interval), 
                      number: 1000 , 
                      //from : to*1000,
											watch : true,
											noFill: false
                    }))});
    },
    getBars(symbolInfo, resolution, from, to, onHistoryCallback, onErrorCallback, firstDataRequest,copycallback) {
      let that = this;
      if (that.interval !== resolution) {
        that.$store.state.resolution = that.resolutions_map.get(resolution);
        if(that.$route.fullPath=="/future"){
          this.win$.wsmsg.sendWsMsg({futureBar : wsmsg.FutureBarRequest.create(this.win$.wsmsg.addRequestId({
										symbol: that.symbol, 
										watch : true,
                    noFill: true,
                    type:'MN1'
                }))
          }) 
        }else{
          that.win$.wsmsg.sendWsMsg({bar : wsmsg.BarRequest.create(that.win$.wsmsg.addRequestId({
											symbol: that.symbol,
											type  : that.resolutions_map.get(resolution), 
                      number: 1000 , 
                      from : to*1000,
											watch : true,
											noFill: true
                    }))});
          } 
        }
         
      //that.s =  onHistoryCallback;
        event.$on('onhistorycallback', function (msg) {
            onHistoryCallback(msg)
        })
       
    },
    subscribeBars(symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback){
        this.onRealtimeCallback(function(e){
            onRealtimeCallback(e);
        });
    },
    
    changecharttype(){
      this.widget.chart().setResolution(that.resolutions_map.get(resolution));
    },
    createButton(buttons){
      let that = this;
      let thats = this.widget;
        for(var i = 0; i < buttons.length; i++){
              (function(button){
                thats.createButton()
                  .attr('title', button.title).addClass("mydate")
                  .text(button.title)
                  .on('click', function(e) {
                      if($(this).parent().hasClass('active')){
                              return false;
                      }
                      localStorage.setItem('tradingview.resolution',button.resolution);
                      localStorage.setItem('tradingview.chartType',button.chartType);
                      $(this).parent().addClass('active').siblings('.active').removeClass('active');
                      thats.chart().setResolution(button.resolution, function onReadyCallback() {});
                      if(button.chartType != thats.chart().chartType()){
                              thats.chart().setChartType(button.chartType);
                              toggleStudy(button.chartType);
                      }
                  }).parent().addClass('my-group'+(button.resolution==that.interval ? ' active':''));
            })(buttons[i]);
        }
    }
  },
  mounted() {
    this.init(this.$route.query.symbol?this.$route.query.symbol:"BTCUSDT",this.initinterval?this.initinterval:5);
  },

  destroyed() {
    if (this.widget !== null) {
      this.widget = null;
    }
  }
}
</script>

